function sortByGuide(arr, guide) {
    var stays = new Set()
    var sorts = [];
    for (var i = 0; i < guide.length; i++) {
        var e = arr[i];
        var idx = guide[i];
        if (idx === -1) {
            stays.add(i);
        } else {
            sorts.push([e, idx])
        }
    }
    sorted = sorts.sort((a, b) => a[1] - b[1]).map(v => v[0]);
    var res = [];
    for (var i = 0; i < arr.length; i++) {
        if (stays.has(i)) res.push(arr[i])
        else res.push(sorted.shift());
    }
    return res;
}
var s = sortByGuide([56, 78, 3, 45, 4, 66, 2, 2, 4], [3, 1, -1, -1, 2, -1, 4, -1, 5])
console.log(s)